import * as boom from '@hapi/boom';
import * as userService from './service.user';
import * as loginPasswordService from './service.login-password';

import { User } from './model';
import { validatePassword, validateUsername } from '../validate';

export async function getUserByUserId(userId: number): Promise<User> {
  const $user = await userService.findByUserId(userId);
  if (!$user) {
    throw boom.notFound(`找不到用户: ${userId}`);
  }
  return $user;
}

export async function getUserByUsername(username: string): Promise<User> {
  const $user = await userService.findByUsername(username);
  if (!$user) {
    throw boom.notFound(`找不到用户: ${username}`);
  }
  return $user;
}

export async function register(username: string, password: string): Promise<void> {
  validateUsername(username);
  validatePassword(password);

  if (await userService.findByUsername(username)) {
    throw boom.conflict(`用户名 ${username} 已经被使用了`);
  }

  const user = await userService.newUser(username);
  await loginPasswordService.save(user.id, password);
}

export async function login(username: string, password: string): Promise<boolean> {
  validateUsername(username);
  validatePassword(password);

  const $user = await userService.findByUsername(username);
  if (!$user) {
    return false;
  }

  return await loginPasswordService.check($user.id, password);
}
